package com.songshuai.customer.client.service.impl;


import com.songshuai.customer.client.dao.customer.CustomerActionMapper;
import com.songshuai.customer.client.dao.customer.FrontSopMapper;
import com.songshuai.customer.client.dao.customer.LabelSopRelationMapper;
import com.songshuai.customer.client.dao.customer.PushRecordMapper;
import com.songshuai.customer.client.dto.request.frontsop.ArticleSopReqDto;
import com.songshuai.customer.client.dto.request.frontsop.CloseViewReqDto;
import com.songshuai.customer.client.dto.request.frontsop.GoodReqDto;
import com.songshuai.customer.client.dto.response.frontsop.ArticleSopResDto;
import com.songshuai.customer.client.service.FrontSopService;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.enumerations.sales.CustomerActionEnum;
import com.songshuai.webapi.baseapi.enumerations.sales.error.SopError;
import com.songshuai.webapi.baseapi.exception.BusinessException;
import com.songshuai.webapi.baseapi.model.sales.*;
import com.songshuai.webapi.baseapi.utils.DateUtil;
import com.songshuai.webapi.baseapi.utils.PropertiesUtil;
import com.songshuai.webapi.baseapi.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FrontSopServiceImpl implements FrontSopService {


    @Autowired
    private SnowFlakeUtil snowFlakeUtil;
    @Autowired
    private CustomerActionMapper customerActionMapper;
    @Autowired
    private FrontSopMapper sopMapper;
    @Autowired
    private LabelSopRelationMapper labelSopRelationMapper;
    @Autowired
    private PushRecordMapper pushRecordMapper;

    @Override
    public void closeView(CloseViewReqDto closeViewReqDto) {

        //参数校验
        if( StringUtils.isEmpty(closeViewReqDto.getViewId()) ){
            throw new BusinessException(SopError.ERROR_SOP_VIEWID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

        CustomerAction customerAction = customerActionMapper.selectByPrimaryKey(closeViewReqDto.getViewId());
        if(customerAction == null){
            throw new BusinessException(SopError.ERROR_SOP_VIEWID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{

            Date startTime = customerAction.getLookTime();
            Date endTime = new Date();
            int second = DateUtil.calcSecond(startTime, endTime);
            customerAction.setBrowseTime(second);
            customerActionMapper.updateByPrimaryKey(customerAction);

        }catch (Exception e) {
            log.error("api/cust/my/closeView", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }





    @Override
    public void goodSop(GoodReqDto goodReqDto) {

        //参数校验
        if( StringUtils.isEmpty(goodReqDto.getSopId()) ){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

        Sop sopCheck = sopMapper.selectByPrimaryKey(goodReqDto.getSopId());
        if(sopCheck == null || sopCheck.getIsDelete() == 1){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{
            sopCheck.setGoodNum(sopCheck.getGoodNum().intValue()+1);
            sopMapper.updateByPrimaryKey(sopCheck);

            //点赞记录
            this.addSopActionRecord(CustomerActionEnum.good.getCode(),goodReqDto.getSopId(),goodReqDto.getCurrentUserId());

        }catch (Exception e) {
            log.error("api/cust/my/goodSop", e);
            throw new BusinessException(ResultStatus.ERROR_UPDATE_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }


    }

    /** 更新推送记录文章状态
     * String sopId 资源ID
     * String userId 浏览人
     **/
    private void updatePushRecordStatus(String sopId, String userId){
        PushRecord pushRecord = new PushRecord();
        pushRecord.setSopId(sopId);
        pushRecord.setReciveUser(userId);
        pushRecord.setIsOpen(0);

        Date date = new Date();
        List<PushRecord> lists = pushRecordMapper.selectByEntityList(pushRecord);
        if(lists!=null && lists.size() > 0){
            for(PushRecord record:lists){
                record.setIsOpen(1);
                record.setOpenTime(date);
                pushRecordMapper.updateByPrimaryKey(record);
            }
        }
    }

    /**
     * 添加浏览记录
     * Integer type (1:浏览,2:分享,3:点赞,4:评价)
     * String sopId 浏览资源
     * String userId 浏览人
     */
    private String addSopActionRecord(Integer type, String sopId, String userId){

        CustomerAction entity = new CustomerAction();
        entity.setId(snowFlakeUtil.nextId());
        entity.setSopId(sopId);
        entity.setAction(type);
        entity.setActionUser(userId);
        entity.setLookTime(new Date());
        customerActionMapper.insert(entity);

        return entity.getId();
    }


    @Override
    public ArticleSopResDto articleSop(ArticleSopReqDto articleSopReqDto) {

        //参数校验
        if( StringUtils.isEmpty(articleSopReqDto.getSopId()) ){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_NULL.getMsg(), ResultStatus.FAILOfficial);
        }

        Sop sopCheck = sopMapper.selectByPrimaryKey(articleSopReqDto.getSopId());
        if(sopCheck == null || sopCheck.getIsDelete() == 1){
            throw new BusinessException(SopError.ERROR_SOP_ID_NOT_EXIST.getMsg(), ResultStatus.FAILOfficial);
        }


        try{

            //浏览+1
            sopCheck.setClickNum(sopCheck.getClickNum().intValue()+1);
            sopMapper.updateByPrimaryKey(sopCheck);

            //添加浏览记录
            String viewId = this.addSopActionRecord(CustomerActionEnum.View.getCode(), articleSopReqDto.getSopId(), articleSopReqDto.getCurrentUserId());
            //更新推送记录文章状态
            this.updatePushRecordStatus(articleSopReqDto.getSopId(), articleSopReqDto.getCurrentUserId());

            ArticleSopResDto articleSopResDto = new ArticleSopResDto();
            PropertiesUtil.copyProperties(sopCheck, articleSopResDto);
            articleSopResDto.setCreateTime(sopCheck.getCreateTime());
            articleSopResDto.setUpdateTime(sopCheck.getUpdateTime());
            articleSopResDto.setViewId(viewId);

            //标签属性
            LabelSopRelation labelSopRelation = new LabelSopRelation();
            labelSopRelation.setSopId(articleSopReqDto.getSopId());
            List<Label> labels =  labelSopRelationMapper.selectLabelsForSopId(labelSopRelation);

            articleSopResDto.setLabels(labels);
            return articleSopResDto;

        }catch (Exception e) {
            log.error("api/cust/my/articleSop", e);
            throw new BusinessException(ResultStatus.ERROR_SEARCH_FAILED.getErrorMsg(), ResultStatus.FAILOfficial);
        }

    }


}
